package com.jiuyin.dianjing.ui.activity.gameInfo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.ItemClickAdapter;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.CommentItemModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.ClipBoardUtil;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.HeaderViewPager;
import com.jiuyin.dianjing.view.RichWebView;
import com.jiuyin.dianjing.view.SlowlyProgressBar;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CONTENT;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_HEAD_URL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INFORMATIONID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INFORMATION_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INTRO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TITLE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_URL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.LIKE_NOT_OK;
import static com.jiuyin.dianjing.api.constant.ApiConstant.LIKE_OK;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;

/**
 * 资讯详情界面
 */
public class GameInfoDetailActivity extends BaseActivity {
    private static final String UMENG_SOCIALIZE_COPY = "umeng_socialize_copy";
    private static final String UMENG_SOCIALIZE_COPYURL = "umeng_socialize_copyurl";
    @BindView(R.id.iv_rightMenu)
    ImageView mImgRightMenu;
    @BindView(R.id.etd_comment)
    EditText mEdtComment;
    @BindView(R.id.web_container)
    RichWebView mWebView;
    @BindView(R.id.nested_container)
    HeaderViewPager mContainer;
    @BindView(R.id.rcv_page)
    RecyclerView mRcvPage;
    private Bitmap mSharedBitmap;
    private UMShareListener mShareListener;
    private ShareAction mShareAction;
    private int mPageNum = PAGE_FIRST;
    private String mInformationId;
    /**
     * 没有评论(true),其它(false)
     */
    private boolean mNoComment = false;

    //资讯链接
    private String mUrl;
    //资讯Title
    private String mTitle;

    private String mSharedUrl;
    /**
     * 简介
     */
    private String mIntro;
    /**
     * 评论列表是否都加载完毕 true(完毕)
     */
    private boolean mCommentLoadedEnd;
    /**
     * 是否可以加载RecyclerView
     */
    private boolean mStartLoadRv;
    private String mCopyText;
    private String mCopyLink;
    private ItemClickAdapter<CommentItemModel> mAdapter;
    private List<CommentItemModel> mListCommentItemModel;
    /**
     * 屏幕高度
     */
    private int mHeightPixels;
    private SlowlyProgressBar mSlowlyProgressBar;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_game_info_detail;
    }

    @Override
    protected void initData() {
        mCopyText = getString(R.string.copy_text);
        mCopyLink = getString(R.string.copy_link);
        mSlowlyProgressBar = new SlowlyProgressBar(findViewById(R.id.ProgressBar));
        Intent intent = getIntent();
        if (null != intent) {
            mUrl = intent.getStringExtra(KEY_URL);
            mTitle = intent.getStringExtra(KEY_TITLE);
            mInformationId = intent.getStringExtra(KEY_INFORMATIONID);
            mSharedUrl = intent.getStringExtra(KEY_HEAD_URL);
            mIntro = intent.getStringExtra(KEY_INTRO);

            if (!TextUtils.isEmpty(mSharedUrl)) {
                Glide.with(GameInfoDetailActivity.this).asBitmap().load(mSharedUrl).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        mSharedBitmap = resource;
                    }
                });
            }
            LogUtil.log(String.format("mUrl = %s,mTitle =%s,mSharedUrl =%s,mInformationId=%s,mIntro=%s", mUrl, mTitle, mSharedUrl, mInformationId, mIntro));
            mImgRightMenu.setImageResource(R.drawable.img_share);
            mImgRightMenu.setVisibility(View.VISIBLE);
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    if (null != mSlowlyProgressBar) {
                        mSlowlyProgressBar.onProgressStart();
                    }
                }
            });
            mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (null != mSlowlyProgressBar) {
                        mSlowlyProgressBar.onProgressChange(newProgress);
                    }
                }
            });
            WebSettings settings = mWebView.getSettings();
            setWebViewSettings(settings);
            mWebView.addJavascriptInterface(this, "androidProxy");
            mWebView.loadUrl(mUrl);
            LogUtil.log(" mUrl = " + mUrl);
            //滚动绑定
            mContainer.setCurrentScrollableContainer(() -> mRcvPage);
            mContainer.setOnScrollListener((currentY, maxY) -> {
                if (maxY > 0 && currentY >= maxY - mHeightPixels) {
                    if (!mStartLoadRv) {
                        mStartLoadRv = true;
                        if (null != mListCommentItemModel) {
                            int size = mListCommentItemModel.size();
                            if (0 != size) {
                                onRefresh(mListCommentItemModel);
                            } else {
                                if (View.VISIBLE != mRcvPage.getVisibility()) {
                                    mRcvPage.setVisibility(View.VISIBLE);
                                }
                                mNoComment = true;
                                mAdapter.addHeaderView(getHeaderNoCommentView());
                            }
                        } else {
                            if (View.VISIBLE != mRcvPage.getVisibility()) {
                                mRcvPage.setVisibility(View.VISIBLE);
                            }
                            mNoComment = true;
                            mAdapter.addHeaderView(getHeaderNoCommentView());
                        }
                    }
                }
            });
            mRcvPage.setItemAnimator(new DefaultItemAnimator());
            mRcvPage.setAdapter(getAdapter());
            mRcvPage.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    // 当不滚动时
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        //获取最后一个完全显示的ItemPosition
                        int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = manager.getItemCount();

                        // 判断是否滚动到底部，并且是向右滚动
                        if (!mNoComment && 0 != totalItemCount && lastVisibleItem == (totalItemCount - 1)) {
                            getCommentList(mInformationId);
                        }
                    }
                }
            });
            initShare();
            Resources resources = getResources();
            //获取屏幕数据
            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
            //获取屏幕宽高，单位是像素
            mHeightPixels = displayMetrics.heightPixels;
        }
    }

    /**
     * 再次加载URL,清空mAdapter
     *
     * @return
     */
    private ItemClickAdapter getAdapter() {
        if (null == mAdapter) {
            mAdapter = new ItemClickAdapter<CommentItemModel>() {
                @Override
                public int getLayoutId() {
                    return R.layout.item_info_comment;
                }

                @Override
                public int getType() {
                    return CommentItemModel.CLICK_ITEM_VIEW;
                }

                @Override
                protected void convert(@NonNull BaseViewHolder holder, CommentItemModel model) {
                    if (null != model) {
                        holder.setText(R.id.tv_comment_title, model.getTitle());
                        holder.setText(R.id.tv_comment_content, model.getComment());
                        holder.setText(R.id.tv_comment_like, model.getLike());
                        holder.setText(R.id.tv_comment_time, model.getTime());
                        ImageView imageView = holder.getView(R.id.img_comment);
                        ImageView commentView = holder.getView(R.id.img_comment_like);
                        commentView.setSelected(LIKE_OK.equals(model.isLike()));
                        Glide.with(GameInfoDetailActivity.this).load(model.getImgUrl()).into(imageView);
                    }
                }
            };
            mAdapter.addChildClickViewIds(R.id.img_comment_like);
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                CommentItemModel model = mAdapter.getData().get(position);
                if (null != model) {
                    ImageView commentView = (ImageView) view;
                    if (null != commentView) {
                        boolean isSelected = commentView.isSelected();
                        HashMap<String, Object> params = new HashMap<>();
                        params.put(KEY_TARGETID, model.getCommentId());
                        params.put(KEY_TOKEN, HelperApplication.getToken());
                        JSONObject jsonObject = new JSONObject(params);
                        if (isSelected) {
                            getApiHelper().appCancelThumb(jsonObject.toString(), data -> {
                                model.setIsLike(LIKE_NOT_OK);
                                model.setLike(data);
                                adapter.notifyDataSetChanged();

                            });
                        } else {
                            getApiHelper().appThumb(jsonObject.toString(), data -> {
                                model.setLike(data);
                                model.setIsLike(LIKE_OK);
                                adapter.notifyDataSetChanged();
                            });
                        }
                    }
                }
            });
        }
        return mAdapter;
    }

    @Override
    protected void initView() {
        setTitle(R.string.detail_info_title);
        firstGetCommentList(mInformationId);
    }

    @SuppressLint("JavascriptInterface")
    private void setWebViewSettings(WebSettings settings) {
        // 设置WebView支持JavaScript
        settings.setJavaScriptEnabled(true);
        //支持自动适配
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);  //支持放大缩小
        settings.setBuiltInZoomControls(false); //显示缩放按钮
        settings.setBlockNetworkImage(false);// 把图片加载放在最后来加载渲染
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setSaveFormData(true);
        settings.setGeolocationEnabled(true);
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);/// 支持通过JS打开新窗口
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    }

    public void onRefresh(Collection<CommentItemModel> models) {
        if (View.VISIBLE != mRcvPage.getVisibility()) {
            mRcvPage.setVisibility(View.VISIBLE);
        }
        int size = models.size();
        if (PAGE_FIRST == mPageNum) {
            mAdapter.addHeaderView(getHeaderView());
            mAdapter.replaceData(models);
        } else {
            if (0 != size) {
                mAdapter.addData(models);
            }
        }
        LogUtil.log("onRefresh size = " + size);
        if (!mCommentLoadedEnd && size < PAGE_NUM) {
            mCommentLoadedEnd = true;
            mAdapter.addFooterView(getFooterView());
        }
        mPageNum++;
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.comment_header, mRcvPage, false);
        return view;
    }

    private View getHeaderNoCommentView() {
        View view = getLayoutInflater().inflate(R.layout.comment_header_no_comment, mRcvPage, false);
        return view;
    }

    private View getFooterView() {
        View view = getLayoutInflater().inflate(R.layout.comment_footer, mRcvPage, false);
        return view;
    }

    @OnClick({R.id.iv_rightMenu, R.id.img_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_send:
                String input = mEdtComment.getText().toString();
                if (!TextUtils.isEmpty(input)) {
                    mEdtComment.setText("");
                    IMEUtil.hideInputMethod(GameInfoDetailActivity.this);
                    comment(input);
                }
                break;
            case R.id.iv_rightMenu:
                share();
                break;
            default:
                break;
        }
    }

    private void share() {
        if (null != mShareAction) {
            mShareAction.open();
        }
    }

    /**
     * 发表评论
     */
    private void comment(String content) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_CONTENT, content);
        params.put(KEY_INFORMATIONID, mInformationId);
        params.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject jsonObject = new JSONObject(params);
        getApiHelper().appCommentInformation(jsonObject.toString(), data -> {
            mContainer.scrollToHeadViewEnd();
            //跳转到第一条
            int size = mAdapter.getData().size();
            if (0 == size) {
                mAdapter.removeAllHeaderView();
                mAdapter.addHeaderView(getHeaderView());
            }
            mAdapter.addData(0, data);
            mRcvPage.smoothScrollToPosition(0);
        });
    }

    /**
     * 初始化分享
     */
    private void initShare() {
        mShareListener = new CustomShareListener(this);
        mShareAction = new ShareAction(GameInfoDetailActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN,
                SHARE_MEDIA.SINA)
                .addButton(mCopyText, mCopyText, UMENG_SOCIALIZE_COPY, UMENG_SOCIALIZE_COPY)
                .addButton(mCopyLink, mCopyLink, UMENG_SOCIALIZE_COPYURL, UMENG_SOCIALIZE_COPYURL)
                .setShareboardclickCallback((snsPlatform, share_media) -> {
                    if (snsPlatform.mShowWord.equals(mCopyText) || snsPlatform.mShowWord.equals(mCopyLink)) {
                        ClipBoardUtil.copy(getApplicationContext(), mUrl);
                        ToastUtil.showShort(R.string.copy_success);
                    } else {
                        UMWeb web = new UMWeb(mUrl);
                        web.setDescription(mUrl);
                        if (!TextUtils.isEmpty(mTitle)) {
                            web.setTitle(mTitle);
                        }
                        if (null != mSharedBitmap) {
                            web.setThumb(new UMImage(GameInfoDetailActivity.this, mSharedBitmap));
                        }
                        if (!TextUtils.isEmpty(mIntro)) {
                            web.setDescription(mIntro);
                        }
                        new ShareAction(GameInfoDetailActivity.this).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(mShareListener)
                                .share();
                    }
                });
    }

    @JavascriptInterface
    public void showDialog(String content) {
        if (!TextUtils.isEmpty(content)) {
            try {
                finish();
                LogUtil.log("showDialog mUrl = " + content);
                JSONObject jsonObject = new JSONObject(content);
                mUrl = jsonObject.getString(KEY_URL);
                mInformationId = jsonObject.getString(KEY_INFORMATION_ID);
                Bundle bundle = new Bundle();
                bundle.putString(KEY_URL, mUrl);
                bundle.putString(KEY_INFORMATIONID, mInformationId);
                goTargetActivity(GameInfoDetailActivity.class, bundle);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取评论列表
     *
     * @param informationId
     */
    private void getCommentList(String informationId) {
        LogUtil.log("getCommentList mCommentLoadedEnd " + mCommentLoadedEnd);
        if (!mCommentLoadedEnd) {
            HashMap<String, Object> params = new HashMap<>();
            params.put(KEY_TOKEN, HelperApplication.getToken());
            params.put(KEY_NUM, mPageNum);
            params.put(KEY_INFORMATIONID, informationId);
            JSONObject jsonObject = new JSONObject(params);
            getApiHelper().appAllInformationDetail(jsonObject.toString(), data -> {
                if (null != data) {
                    String url = data.getImgUrl();
                    if (!TextUtils.isEmpty(url)) {
                        if (!url.equals(mSharedUrl)) {
                            mSharedUrl = url;
                            loadSharedImg(url);
                        }
                    }
                    mTitle = data.getTitle();
                    List<CommentItemModel> commentItemModelList = data.getListCommentItemModel();
                    if (null != commentItemModelList) {
                        int size = commentItemModelList.size();
                        if (0 != size) {
                            onRefresh(commentItemModelList);
                        }
                    }
                }
            });
        }
    }

    /**
     * 进入详情获取评论列表
     *
     * @param informationId
     */
    private void firstGetCommentList(String informationId) {
        LogUtil.log("firstGetCommentList informationId = " + informationId);
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_NUM, mPageNum);
        params.put(KEY_INFORMATIONID, informationId);
        JSONObject jsonObject = new JSONObject(params);
        LogUtil.log("firstGetCommentList informationId = " + jsonObject.toString());
        getApiHelper().appAllInformationDetail(jsonObject.toString(), data -> {
            if (null != data) {
                String url = data.getImgUrl();
                if (!TextUtils.isEmpty(url)) {
                    if (!url.equals(mSharedUrl)) {
                        mSharedUrl = url;
                        loadSharedImg(url);
                    }
                }
                mTitle = data.getTitle();
                mListCommentItemModel = data.getListCommentItemModel();
            }
        });
    }

    /**
     * 加载分享url
     *
     * @param url
     */
    private void loadSharedImg(String url) {
        if (!TextUtils.isEmpty(url)) {
            Glide.with(GameInfoDetailActivity.this).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    mSharedBitmap = resource;
                }
            });
        }
    }

    private static class CustomShareListener implements UMShareListener {
        private WeakReference<GameInfoDetailActivity> mActivity;

        private CustomShareListener(GameInfoDetailActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST
                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST
                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (mSlowlyProgressBar != null) {
            mSlowlyProgressBar.destroy();
            mSlowlyProgressBar = null;
        }
    }
}
